package com.example.mybank.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mybank.entity.Debit;
import com.example.mybank.entity.Users;
import com.example.mybank.mapper.DebitMapper;
import com.example.mybank.mapper.UsersMapper;
import com.example.mybank.tool.MyException;
import com.example.mybank.tool.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Random;

@Slf4j
@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    UsersMapper usersMapper;

    @Autowired
    DebitMapper debitMapper;

    // 管理员：获取获取所有用户
    @GetMapping("/all")
    public List<Users> getAll(){
        return usersMapper.selectList(null);
    }

    /**
     * 普通用户注册
     * @param users
     * @return
     */
    @PostMapping("/register")
    public Boolean add(@RequestBody Users users) throws MyException {
        users.setIs_admin(Boolean.FALSE);
        Date date = new Date();
        users.setDatetime_register(date);

        QueryWrapper<Users> queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",users.getUsername());
        List<Users> users1 = usersMapper.selectList(queryWrapper);
        if(users1.size()>0){
            throw new MyException(ResultCode.USER_IS_EXIST);
        }

        usersMapper.insert(users);
        return true;
    }



    @GetMapping("/registerByUsername/{username}")
    public Boolean deleteAndAdd(@PathVariable("username") String username) throws MyException {
        Random random = new Random();

        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        usersMapper.delete(queryWrapper);

        int age = 20;
        Users users = new Users(0L, username, "0", username, "123456", Boolean.TRUE, age, Boolean.TRUE, Boolean.FALSE, null, null);
        add(users);

        return Boolean.TRUE;
    }


    /**
     * 管理员注册
     * @param users
     * @return
     */
    @PostMapping("/registerAdmin")
    public Boolean admin(@RequestBody Users users){
        users.setIs_admin(true);
        usersMapper.insert(users);
        return true;
    }





}
